package rwt.server.railroad;

import java.util.*;

import rwt.server.WebMessages.CloseSwitches;
import rwt.server.WebMessages.OpenSwitchesResponse;
import rwt.server.core.*;

public class Switches
{
	private static final Switches instance = new Switches();
	public static Switches getInstance()
	{
		return instance;
	}
	
	//--------------------------------------------------------------------------
	
	private boolean emergencyOpen = false;
	private int emergencyId = 0;
	
	/** User IDs of clients with a Switches window open. Mapped to number of Switches windows */
	private Map<IClient, Integer> clientIds = new HashMap<>();
	
	//Handles client request for switches page
	public void addClientSwitches(IClient client, boolean isEmergency, int switchType)
	{
		boolean granted = false;
		if (isEmergency)
		{
			//TODO: Check if admin
			closeAll();
			clientIds.put(client, 1);
			emergencyId = client.getId();
			emergencyOpen = true;
			granted = true;
		}
		
		if (!emergencyOpen)
		{
			if (clientIds.containsKey(client))
			{
				clientIds.put(client, clientIds.get(client) + 1);
			} else {
				clientIds.put(client, 1);
			}
			granted = true;
		} 
		OpenSwitchesResponse res = new OpenSwitchesResponse(granted, switchType);
		client.write(res);
	}
	
	//Removes one client switches page
	public void removeClientSwitches(IClient client)
	{
		if (clientIds.containsKey(client))
		{
			int numSwitches = clientIds.get(client) - 1;
			
			if (emergencyOpen && emergencyId == client.getId())
			{
				emergencyId = 0;
				emergencyOpen = false;
			}
			if (numSwitches == 0)
			{
				clientIds.remove(client);
			} else {
				clientIds.put(client, numSwitches);
			}
		}
	}
	
	//Removes all switches for a client
	public void removeClient(IClient client)
	{
		if (clientIds.containsKey(client))
		{
			if (emergencyOpen && emergencyId == client.getId())
			{
				emergencyId = 0;
				emergencyOpen = false;
			}
			clientIds.remove(client);
		}
	}
	
	public void sendToAll(BaseMessage msg)
	{
		for (IClient client : clientIds.keySet())
		{
			client.write(msg);
		}
	}
	
	//Close all switch pages
	public void closeAll()
	{
		emergencyId = 0;
		emergencyOpen = false;
		CloseSwitches msg = new CloseSwitches();
		sendToAll(msg);
		clientIds.clear();
	}
	
	public boolean isValid(IClient client)
	{
		if (emergencyOpen)
		{
			if (emergencyId == client.getId())
			{
				return true;
			}
			return false;
		}
		return true;
	}
	
	public boolean isEmergency()
	{
		return emergencyOpen;
	}
}
